<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="utf-8">
    <title>浏览页面</title>
    <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
    <link rel="stylesheet" href="/app/admin/admin/css/reset.css" />
    <style>
        .c-item {
            width: auto !important;
        }

        .c-label {
            width: auto !important;
            padding: 9px 5px 9px 15px !important;
        }

        .c-inline {
            width: auto !important;
        }

        .layui-text-em {
            color: #333 !important;
        }

        .onMake {
            background-color: #fe3666 !important;
        }

        .layui-form-mid {
            margin-left: 0 !important;
        }
    </style>
</head>

<body class="pear-container">

    <!-- 顶部查询表单 -->
    <div class="layui-card">
        <div class="layui-card-body">
            <form class="layui-form top-search-from">

                <div class="layui-form-item c-item" style="margin-left: 16px;">
                    <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="table-query">
                        <i class="layui-icon layui-icon-util"></i>设置店铺
                    </button>
                </div>

                <div class="layui-form-item c-item">
                    <label class="layui-form-label c-label">店铺：</label>
                    <div class="layui-input-inline c-inline">
                        <div class="layui-form-mid layui-text-em" id="shop_name">-</div>
                    </div>
                </div>

                <div class="layui-form-item c-item">
                    <label class="layui-form-label c-label">店内分类：</label>
                    <div class="layui-input-inline c-inline">
                        <div class="layui-form-mid layui-text-em" id="shop_category_name">-</div>
                    </div>
                </div>

                <div class="layui-form-item c-item">
                    <label class="layui-form-label c-label">价格增加：</label>
                    <div class="layui-input-inline c-inline">
                        <div class="layui-form-mid layui-text-em" id="price">-</div>
                    </div>
                </div>

                <div class="layui-form-item c-item">
                    <label class="layui-form-label c-label">上传方式：</label>
                    <div class="layui-input-inline c-inline">
                        <div class="layui-form-mid layui-text-em" id="add_type">-</div>
                    </div>
                </div>

                <div class="layui-form-item c-item" style="float: right;">
                    <div class="layui-form-mid layui-text-em">
                        总数量：<label id="goodsDataCount">0</label>
                        &emsp;已执行：<label id="upNum">0</label>
                        &emsp;成功：<label id="makeSuccess">0</label>
                        &emsp;已存在：<label id="makeExist">0</label>
                        &emsp;失败：<label id="makeError">0</label>
                    </div>
                    <a class="pear-btn pear-btn-danger pear-btn-md" layui-on="test">执行</a>
                    <!-- &emsp;<button class="pear-btn pear-btn-danger pear-btn-md" id="onMake" layui-on="onMake"
                        type="button"><i class="layui-icon layui-icon-play"></i>&thinsp;开始执行</button>
                    <button class="pear-btn pear-btn-danger pear-btn-md" id="onMakeIng" style="display: none;"
                        type="button"><i
                            class="layui-icon layui-anim layui-anim-rotate layui-anim-loop">&#xe63d;</i>&thinsp;正在执行</button> -->
                </div>

                <div class="toggle-btn">
                    <a class="layui-hide">展开<i class="layui-icon layui-icon-down"></i></a>
                    <a class="layui-hide">收起<i class="layui-icon layui-icon-up"></i></a>
                </div>
            </form>
        </div>
    </div>

    <!-- 数据表格 -->
    <div class="layui-card">
        <div class="layui-card-body">
            <table id="data-table" lay-skin="table" lay-filter="data-table"></table>
        </div>
    </div>

    <!-- 表格顶部工具栏 -->
    <script type="text/html" id="table-toolbar">
            <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add" permission="app.admin.shop.insert">
                <i class="layui-icon layui-icon-add-1"></i>导入SPU
            </button>
            <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchRemove" permission="app.admin.shop.delete">
                <i class="layui-icon layui-icon-delete"></i>清空数据
            </button>
        </script>

    <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.2.1/jquery.min.js"></script>
    <script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
    <script src="/app/admin/component/pear/pear.js"></script>
    <script src="/app/admin/admin/js/permission.js"></script>
    <script src="/app/admin/admin/js/common.js"></script>

    <script>

        // 相关常量
        const PRIMARY_KEY = "id";

        // 表格渲染
        layui.use(["table", "form", "common", "popup", "util"], function () {
            let table = layui.table;
            let form = layui.form;
            let $ = layui.$;
            let common = layui.common;
            let util = layui.util;

            let taskInfo; // 任务缓存

            let allNum = 0;
            let tasks = layui.data('tasks');
            let upNum = 0;
            if (tasks.upNum) {
                upNum = tasks.upNum;
            }
            if (tasks.tasksUpNum) {
                upNum = tasks.tasksUpNum;
            }

            // 表头参数
            let cols = [
                {
                    // type: 'numbers', title: '#', width: 100
                    field: 'numbers', title: '#', width:100, templet: function(d){
                        return d.LAY_INDEX;
                    }, align: "center",
                }, 
                {
                    title: "商品Id", align: "left",
                    field: "spu_id", width: 150
                }, {
                    title: '商品名称', field: 'title',
                    templet: function (d) {
                        return jQuery.isArray(d.goodsInfo) && d.goodsInfo.length === 0 ? '' : '<div style="line-height: 20px!important">' + d.goodsInfo.item.title + '</div>'
                    }, align: 'left'
                }, {
                    title: '解析状态', templet: function (d) {
                        for (var i = 3; i >= 0; i--) {
                            if (d.anaStatus == 1) {
                                return '<span class="layui-badge-dot layui-bg-blue"></span>&nbsp;成功';
                            } else if (d.anaStatus == 2) {
                                return '<span class="layui-badge-dot"></span>&nbsp;失败';
                            } else {
                                return '<span class="layui-badge-dot layui-bg-orange"></span>&nbsp;等待';
                            }
                        }
                    }, align: 'center', width: 150
                }, {
                    title: '上传状态', templet: function (d) {
                        for (var i = 3; i >= 0; i--) {
                            if (d.upStatus == 1) {
                                return '<span class="layui-badge-dot layui-bg-blue"></span>&nbsp;成功';
                            } else if (d.upStatus == 2) {
                                return '<span class="layui-badge-dot"></span>&nbsp;失败';
                            } else {
                                return '<span class="layui-badge-dot layui-bg-orange"></span>&nbsp;等待';
                            }
                        }
                    }, align: 'center', width: 150
                }, {
                    title: "信息", align: "left",
                    field: "msg", width: 400
                }
            ];

            // 渲染表格
            render();
            function render() {
                table.render({
                    elem: "#data-table",
                    url: "/app/admin/upload-data/spuList",
                    page: false,
                    limit: 1000,
                    cols: [cols],
                    skin: "line",
                    toolbar: "#table-toolbar",
                    autoSort: false,
                    height: "full-170",
                    defaultToolbar: [{
                        title: "刷新",
                        layEvent: "refresh",
                        icon: "layui-icon-refresh",
                    }, "filter", "print", "exports"],
                    done: function (obj) {
                        // 显示配置数据
                        configView(obj);
                        // 总数据量
                        allNum = obj.count;
                        $("#upNum").text(obj.upNum);
                        // 将总数居存起来，用来矫正数据
                        layui.data('tasks', {
                            key: 'tasksUpNum',
                            value: obj.upNum
                        });
                        upNum = obj.upNum;

                        // 开始执行方法
                        util.on('layui-on', {
                            'onMake': function () {
                                // 判断是否设置了店铺，店内分类，价格增加
                                console.log(taskInfo);
                                if (taskInfo.shopId == '' || taskInfo.shopCategoryId == '' || taskInfo.price_config == '') {
                                    layer.confirm("请先设置店铺", {
                                        icon: 7,
                                        btn: ['确定'],
                                        title: '提示'
                                    });
                                    return false;
                                }
                                if (!timer) { // 防止多次启动多个定时器
                                    startTimer();
                                    $("#onMake").css("display", "none");
                                    $("#onMakeIng").css("display", "inline-block");
                                }
                            },
                            'test': function () {
                                // 判断是否设置了店铺，店内分类，价格增加
                                console.log(taskInfo);
                                if (taskInfo.shopId == '' || taskInfo.shopCategoryId == '' || taskInfo.price_config == '') {
                                    layer.confirm("请先设置店铺", {
                                        icon: 7,
                                        btn: ['确定'],
                                        title: '提示'
                                    });
                                    return false;
                                }
                                upMake(0);
                            }
                        });

                        // 定时执行器
                        var timer; // 定时器的 ID
                        var time = 2; // 2秒执行一次
                        console.log("总数据量：" + allNum);
                        console.log("当前执行：" + upNum);
                        function startTimer() {
                            timer = setInterval(function () {
                                let index = upNum;
                                upNum++;
                                layui.data('tasks', {
                                    key: 'upNum',
                                    value: upNum
                                });
                                if (index == allNum) {
                                    if (timer) {
                                        clearInterval(timer);
                                        // $("#onMake").css("display", "inline-block");
                                        // $("#onMakeIng").css("display", "none");
                                        // layer.confirm('上品执行结束', {
                                        //     btn: ['确认'],
                                        //     icon: 1,
                                        //     title: "提示"
                                        // }, function () {
                                        //     layui.layer.closeAll(); // 关闭提示框
                                        // });
                                    }
                                } else {
                                    $("#upNum").text(index + 1);
                                    upMake(index);
                                }
                            }, 1000 * time);
                        }

                        // 解析上传执行方法
                        let upMake = function (index) {
                            console.log("执行了：" + index + "次");
                            layui.$.ajax({
                                url: "/app/admin/upload-data/upMake",
                                data: { upNum: index },
                                type: "post",
                                dataType: "json",
                                async: true,
                                success: function (res) {
                                    // if (res.code == 0) {
                                    //     if(res.data.type == 1) {
                                    //         clearInterval(timer);
                                    //         $("#onMake").css("display", "inline-block");
                                    //         $("#onMakeIng").css("display", "none");
                                    //         layer.confirm(res.msg, {
                                    //             btn: ['确认'],
                                    //             icon: 2,
                                    //             title: "提示"
                                    //         }, function () {
                                    //             render();
                                    //             layui.layer.closeAll(); // 关闭提示框
                                    //         });
                                    //     } else {
                                    //         if (res.data.count == res.data.upNum) {
                                    //             $("#onMake").css("display", "inline-block");
                                    //             $("#onMakeIng").css("display", "none");
                                    //             layer.confirm('上品执行结束', {
                                    //                 btn: ['确认'],
                                    //                 icon: 1,
                                    //                 title: "提示"
                                    //             }, function () {
                                    //                 render();
                                    //                 layui.layer.closeAll(); // 关闭提示框
                                    //             });
                                    //         }
                                    //     }
                                    //     configView(res.data);
                                    //     console.log(res);
                                    // } else {
                                    //     console.log(res.data);
                                    //     // $("#onMake").css("display", "inline-block");
                                    //     // $("#onMakeIng").css("display", "none");
                                    //     // clearInterval(timer);
                                    //     // layer.confirm(res.msg, {
                                    //     //     btn: ['确认'],
                                    //     //     icon: 2,
                                    //     //     title: "提示"
                                    //     // });
                                    // }
                                },
                                error: function (res) {
                                    return layui.popup.failure("执行失败");
                                }
                            });
                        }

                    }
                });
            }

            // 表格顶部工具栏事件
            table.on("toolbar(data-table)", function (obj) {
                if (obj.event === "add") { // 导入数据
                    spuLeadingIn();
                } else if (obj.event === "refresh") { // 刷新表格
                    refreshTable();
                } else if (obj.event === "batchRemove") { // 清空数据
                    batchRemove(obj);
                }
            });

            // 设置店铺
            form.on("submit(table-query)", function (data) {
                var shop_name = $('#shop_name').text();
                var category_id = $('#category_id').text();
                var price = $('#price').text();
                var field = { shop_name: shop_name, category_id: category_id, price: price };
                layer.open({
                    type: 2,
                    title: "设置店铺",
                    shade: 0.1,
                    maxmin: true,
                    area: [common.isModile() ? "100%" : "600px", common.isModile() ? "100%" : "500px"],
                    content: "/app/admin/upload-data/config",
                    data: field
                });
                return false;
            });

            // 导入数据
            let spuLeadingIn = function () {
                layer.prompt({
                    title: '请输入链接',
                    formType: 2,
                    area: [common.isModile() ? "100%" : "500px", common.isModile() ? "100%" : "450px"],
                    maxlength: 9999999
                }, function (value, index, elem) {
                    if (value === '') return elem.focus();
                    layui.$.ajax({
                        url: "/app/admin/upload-data/dataHandling",
                        data: { 'linkData': value },
                        type: "post",
                        dataType: "json",
                        success: function (res) {
                            layui.data('tasks', null);
                            upNum == 0;
                            console.log(res);
                            if (res.code == 0) {
                                location.reload()
                                layer.close(index);
                            } else {
                                layer.confirm(res.msg, {
                                    icon: 2,
                                    btn: ['确定'],
                                    title: '提示'
                                });
                            }
                        },
                        error: function (res) {
                            layer.confirm("发生错误，请重新操作！", {
                                icon: 2,
                                btn: ['确定'],
                                title: '提示'
                            });
                        }
                    });
                });
            }

            // 清空数据
            let batchRemove = function (obj) {
                layui.layer.confirm('确定要清空数据吗？', {
                    btn: ['确认', '取消'],
                    icon: 3,
                    title: "提示"
                }, function () {
                    layui.data('tasks', null);
                    $.ajax({
                        url: "/app/admin/upload-data/clearLinkData",
                        dataType: "json",
                        type: "post",
                        success: function (res) {
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            location.reload();
                            // return layui.popup.success("操作成功", refreshTable);
                        }
                    })
                    layui.layer.closeAll(); // 关闭提示框
                }, function () {
                    layui.layer.closeAll(); // 关闭提示框
                });
            }

            // 执行清空数据
            let doRemove = function (ids) {
                layer.confirm("确定清空数据?", {
                    icon: 3,
                    title: "提示"
                }, function (index) {
                    layer.close(index);
                    let loading = layer.load();
                    $.ajax({
                        url: "/app/admin/upload-data/clearLinkData",
                        dataType: "json",
                        type: "post",
                        success: function (res) {
                            layer.close(loading);
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", table.reload());
                        }
                    })
                });
            }

            // 刷新表格数据
            window.refreshTable = function () {
                table.reloadData("data-table", {
                    scrollPos: "fixed",
                    done: function (res, curr) {
                        configView(res);
                        if (curr > 1 && res.data && !res.data.length) {
                            curr = curr - 1;
                            table.reloadData("data-table", {
                                page: {
                                    curr: curr
                                },
                            })
                        }
                    }
                });
            }

            // 赋值显示配置
            function configView(obj) {
                taskInfo = obj;
                $("#shop_name").text(obj.shopInfo.name ?? "-");
                $("#shop_category_name").text(obj.shopCategoryName != '' ? obj.shopCategoryName : "-");
                $("#price").text(obj.price_config != "" ? obj.price_config + "%" : "-");
                if(obj.add_type == 1) {
                    $("#add_type").text("单SKU上传");
                } else if(obj.add_type == 2) {
                    $("#add_type").text("多SKU上传");
                } else {
                    $("#add_type").text("-");
                }
                $("#goodsDataCount").text(obj.count);
                $("#makeError").text(obj.error);
                $("#makeSuccess").text(obj.success);
                $("#makeExist").text(obj.exist);
            }
        })

    </script>
</body>

</html>